
import 'dart:math';

import 'package:ceramics/extensions/ab_list_extensions.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_init_db.dart';
import 'package:ceramics/util/ab_oss_fetch_util.dart';
import 'package:ceramics/util/ab_value_converter.dart';
import 'package:get/get.dart';

import 'ab_oauth.dart';

class ABWorks {
  late int id;
  late String images;
  int likes = 0;
  String userId = '';
  String nickname = '';
  String title = '';
  String detail = '';
  String avatar = '';
  OSSResponse? avatarOss;
  String createTime = '';
  int boost = 0;
  var isLiked = false.obs;

  ABWorks({required this.id, required this.images, this.likes = 0, this.userId = '', this.nickname = '', this.avatar = '', this.createTime = '', this.boost = 0, this.title = '',this.detail = ''});

  static homeWorks() async {
    // query works limit 3 high boosts
    var result = await abDB.query('works', orderBy: 'boost desc');
    result = await result.replaceOSSURL({'avatar':'image'});
    var blocks = await api.blockList(loading: false);
    /// 选不在blocks里的前5个作品
    var a = [];
    for (var item in result) {
      if (!blocks.containsWhere((b) => b.broadcasterId == item['userId'])) {
        a.add(item);
      }
      if (a.length == 5) {
        break;
      }
    }
    result = a.cast();
    return arrayFromJSON(result);
  }

  static hotWorks() async {
    var result = await abDB.query('works', orderBy: 'boost desc');
    result = await result.replaceOSSURL({'avatar':'image'});
    var blocks = await api.blockList(loading: false);
    result = result.where((a) => !blocks.containsWhere((b) => b.broadcasterId == a['userId'])).toList();
    return arrayFromJSON(result);
  }

  static Future<List<ABWorks>> worksWithUserId(String userId) async {
    var result = await abDB.query('works', where: 'userId = ?', whereArgs: [userId]);
    result = await result.replaceOSSURL({'avatar':'image'});
    return arrayFromJSON(result);
  }

  static Future<int> insertMyWorks(
      {List<String> images = const <String>[], String title = '', String detail = ''}) async {
    var userId = ABSingleton.user?.userId;
    var nickname = ABSingleton.user?.nickname;
    var avatar = ABSingleton.user?.avatar;
    var createTime = DateTime.now().toIso8601String();
    var boost = 0;
    var id = await abDB.insert('works', {
      'images': images.join(','),
      'likes': 0,
      'userId': userId,
      'nickname': nickname,
      'avatar': avatar,
      'createTime': createTime,
      'boost': boost,
      'title': title,
      'detail': detail,
    });
    return id;
  }

  static deleteWorksWithUserId(String userId) async {
    await abDB.delete('works', where: 'userId = ?', whereArgs: [userId]);
  }

  updateBoost() async {
    await abDB.update('works', {'boost': boost}, where: 'id = $id');
  }


  static arrayFromJSON(List<dynamic> json) {
    List<ABWorks> works = [];
    for (var item in json) {
      works.add(ABWorks.fromJson(item));
    }
    return works;
  }

  static fromJson(Map<String, dynamic> json) {
    var works = ABWorks(
      id: valueToInt(json['id']),
      images: valueToString(json['images']),
      likes: valueToInt(json['likes']),
      userId: valueToString(json['userId']),
      nickname: valueToString(json['nickname']),
      avatar: valueToString(json['avatar']),
      createTime: valueToString(json['createTime']),
      boost: valueToInt(json['boost']),
      title: valueToString(json['title']),
      detail: valueToString(json['detail']),
    );
    works.avatarOss = json['avatar_oss'];
    return works;
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'images': images,
      'likes': likes,
      'userId': userId,
      'nickname': nickname,
      'avatar': avatar,
      'createTime': createTime,
      'boost': boost,
      'title': title,
      'detail': detail,
    };
  }

  Future save() async {
    if (id == -1) {
      id = await abDB.insert('videos', toJson());
    } else {
      await abDB.update('videos', toJson(), where: 'id = ?', whereArgs: [id]);
    }
  }

  static replaceUsers(List<ABUser> users) async {
    var works = await abDB.query('works');
    for (var work in works) {
      var userId = work['userId'];
      if (users.isEmpty) {
        break;
      }
      var randomIdx = Random().nextInt(users.length);
      var randomUser = users[randomIdx];
      await abDB.update('works', {'userId': randomUser.userId, 'nickname': randomUser.nickname, 'avatar': randomUser.avatar}, where: 'userId = ?', whereArgs: [userId]);
      users.removeWhere((element) => element.userId == randomUser.userId);
    }
  }

}